/**
 * Created by TomSean on 2017/7/20.
 */
var ChargesList = function ($parent) {
    this.$parent = $parent;
    this.sysUtils = new kendoUtils();
    this.init();
    return this;
}

ChargesList.prototype = {
    init : function () {
        var $this = this;
        var filedArray = $this.sysUtils.getBindFieldArray($this.$parent.find('.search-panel'));
        var functionArray = [
            {fName: 'search_btn', fs: this.findData},
            {fName: 'reset_btn', fs: this.resetInfo}
        ];
        $this.models = new bindBaseModel(null, filedArray, functionArray, null);
        $this.sysUtils.bindDoucment($this.models, $this.$parent, $this);
        Utils.createDataDictDropDownList({
            div: this.$parent.find('#credentialsType'),
            parentModelKey: BASIS.TRAFFIC_TYPE_CLASS.ROOT
        }, this);
        Utils.createDataDictDropDownList({
            div: this.$parent.find('#payMold'),
            parentModelKey: BASIS.PAY_TYPE.ROOT
        }, this);
        Utils.createDataDictDropDownList({
            div: this.$parent.find('#chagerWay'),
            parentModelKey: BASIS.CHARGE_METHOD.ROOT
        }, this);
        /**
		 * 弹出框获取所有工作站节点树
		 */
		JsonpAjax(baseApiPath + 'layout/wsn/get', '', 'json', function(res) {
			var potionTree = $this.$parent.find("#chargesLog-tree").lonixFloat({
				source: res,
				setting: {
					view: {
						showLine: true,
						selectedMulti: false,
						dblClickExpand: false,
						showIcon: false
					},
					data : {
						simpleData: {
							enable: true,
							idKey: "orgCode",
							pIdKey: "parentCode",
							rootPId:""
						}
					}
				},
				searchField: 'name',
				target: $this.$parent.find("#orgName"),
				primary: function (nodes) {
					if(nodes.length <= 0 ) return;
					$this.$parent.find('#chargesLog-tree').fadeUp();
					$this.parkOrgCode = nodes[0]["orgCode"];
					//显示层级
					$this.$parent.find("#orgName").val(nodes[0]["name"]+"("+$this.parkOrgCode+")");
				}
			});
		}, false);
        $this.initTable();
        $this.findData();
    },
    findData : function (e) {
        var $this = this;
        if (!isEmpty(e)) {
            $this = $(e.target).data('that');
        }
        var grid = $this.$parent.find('#charges_log_data_list').data('kendoGrid');
        var params = $this.sysUtils.getBindDocJson($this.models.bindFieldArray);
        //转换时间格式
        if(isNotEmpt(params["chargeTimeMin"])){
            params["chargeTimeMin"] = kendo.toString(params["chargeTimeMin"],'yyyy-MM-dd HH:mm:ss');
        }
        if(isNotEmpt(params["chargeTimeMax"])){
            params["chargeTimeMax"] = kendo.toString(params["chargeTimeMax"],'yyyy-MM-dd HH:mm:ss');
          //  params["chargeTimeMax"] = params["chargeTimeMax"].split(' ')[0]+' 23:59:59';
        }
        if(null != $this.parkOrgCode){
			params["parkOrgCode"] =  $this.parkOrgCode;
		}
        var dataT = {'jsonParam' : JSON.stringify(params)};

        var dataSource = $this.sysUtils.getDataSource({url : baseApiPath + 'charges_log/list', data : dataT, dataType : 'odata'});
        grid.setDataSource(dataSource);
    },
    initTable : function () {
        var $this = this;
        var columns = [
            {
                title : '卡消费信息',
                template : '#if(data.trafficPermitTypeIdentity == 0){#<div><img src="images/card-temp.png"><span style="">车牌:</span>#:data.vehicleNo#</div>#}else if(data.trafficPermitTypeIdentity == 1){#<div><img src="images/card-mon.png"><span style="">车主:</span>#:data.ownerName#<span>&nbsp;&nbsp;车位:</span>#:data.spaceCode# # if(isNotEmpt(data.payType)&&data.payType==3){if(isNotEmpt(data.vehicles)){#<span>&nbsp;&nbsp;车牌:</span>#:data.vehicles# #}else{#<span style="color: red;">未绑定车牌</span>#}}#</div>#}else if(data.trafficPermitTypeIdentity == 2){#<div><img src="images/card-store.png"><span style="">车主:</span>#:data.ownerName#[#:data.ownerCode#]<span style="">#if(data.vehicleNo != undefined){#&nbsp;&nbsp;车牌:</span>#:data.vehicleNo#</div>#}}#',
                width : 300
            },
            {
                title : '凭证类型',
                template : '#:Utils.getModelNameByParentKey(BASIS.TRAFFIC_TYPE_CLASS.ROOT, data.trafficPermitTypeIdentity == null ? 0 : data.trafficPermitTypeIdentity)#'
            },
            {
                title : '缴费类别',
                template : '#:Utils.getModelNameByParentKey(BASIS.PAY_TYPE.ROOT, payType)#'
            },
            {
                title : '缴费金额',
                field : 'chargeMoney'
            },
            {
                title : '缴费方式',
                template : '#:Utils.getModelNameByParentKey(BASIS.CHARGE_METHOD.ROOT,  data.chargeMethod == null ? "" : data.chargeMethod)#'
            },
           /* {
                title : '车牌号',
                template : "${null==data.vehicleNo? '-' : data.vehicleNo }"
            },
            {
                title : '车位号',
                template : "${null==data.spaceCode? '-' : data.spaceCode }"
            },*/
            {
                title : '优惠金额',
                field : 'preMoney'
            },
            {
                title : '缴费时间',
                field : 'chargeTime'
            },
            {
                title : '收费员',
                field : 'ouUname'
            },
            /*{
                title : '描述',
                field : 'remark'
            }*/
        ];
        $this.sysUtils.createGird($this.$parent.find('#charges_log_data_list'), {
            selectable : 'single',
            autoSync : true,
            columnMenu : true,
            pageable : {input : true, numeric : false},
            columns : columns,
            change : function(e) {
                var selected = $.map(this.select(), function(itm) {
                    return $(itm).find('input[type=checkbox]').val();
                });
                $this.selectRowId = selected[0];
            },
            dataBound:function(){
                $this.$parent.find("#charges_log_data_list").find("tr:gt(0)").unbind("dblclick");
                $this.$parent.find("#charges_log_data_list").find("tr:gt(0)").dblclick(function(e){
                    var grid = $this.$parent.find("#charges_log_data_list").data("kendoGrid");
                    var dataItem = grid.dataItem(grid.select());
                    //打开查看窗口
                    $this.openRecorderWindow(dataItem["id"]);
                });
            }
        });
    },
    /*
     * 重置按钮
     */
    resetInfo:function(e){
        var $this = $(e.target).data("that");
        $this.sysUtils.setBindFieldNull($this.models.bindFieldArray);
    },
    openRecorderWindow:function(id,isEdit){
        var $this = this;
        var titles = "查看缴费详情";
        $this.editResult = null;
        $this.isEdit = null;
        var openwidonw = function(){
            $this.editDiv = $this.sysUtils.openWindow($this.editDiv,{
                title:titles,
                height:"460px",
                width:"730px",
                resizable:false,
                content:"views/parkLotCenter/chargesLog/charges_log_edit.html"
            }, true);
        };
        var ajaxPost = function(){
            JsonpAjax(baseApiPath+"charges_log/" + id,null,"json",function(result){
                $this.editResult = result;
                openwidonw();
            });
        };
        $this.isEdit = false;
        ajaxPost();
    },
    /**
     * 导出Excel文件
     */
    exportExcel:function(){
    	 var params = this.sysUtils.getBindDocJson(this.models.bindFieldArray);
         //转换时间格式
         if(isNotEmpt(params["chargeTimeMin"])){
             params["chargeTimeMin"] = kendo.toString(params["chargeTimeMin"],'yyyy-MM-dd HH:mm:ss');
         }
         if(isNotEmpt(params["chargeTimeMax"])){
             params["chargeTimeMax"] = kendo.toString(params["chargeTimeMax"],'yyyy-MM-dd HH:mm:ss');
         }
         if(null != this.parkOrgCode){
 			params["parkOrgCode"] =  this.parkOrgCode;
 		}
         window.open(baseApiPath+'charges_log/exportExcel?jsonData='+encodeURI(JSON.stringify(params)));
    }
}
var ChargesEdit = function ( targetObj ) {
    this.targetObj = targetObj;
    this.sysUtils = new kendoUtils();
    this.init();
    return this;
}
ChargesEdit.prototype = {
    init : function () {
        var fieldArray = this.sysUtils.getBindFieldArray(this.targetObj);
        var functionArray = [{fName : 'cancel', fs : function () { $('#' + chargesList.editDiv).data('kendoWindow').close(); } }
        ];
        this.models = new bindBaseModel(null, fieldArray, functionArray, null);
        this.sysUtils.bindDoucment(this.models, this.targetObj, this);
        this.loadInfo();
    },
    loadInfo:function () {
        var that = this;
        var entity= chargesList.editResult.entity;
        if(isNotEmpt(entity)){
            entity['payPlatformName']=Utils.getModelNameByParentKey(BASIS.PAY_PLATFORM.ROOT,entity.payPlatform);
            entity['chargeMethodName']=Utils.getModelNameByParentKey(BASIS.CHARGE_METHOD.ROOT,entity.chargeMethod);
            entity['payTypeName']=Utils.getModelNameByParentKey(BASIS.PAY_TYPE.ROOT,entity.payType);
            entity['credentialsName']=Utils.getModelNameByParentKey(BASIS.TRAFFIC_TYPE_CLASS.ROOT,entity.trafficPermitTypeIdentity);
            if(isEmpty(entity.owner)){
                that.targetObj.find('#headerPoto').attr('src','images/icon-default.png');
            }else{
                that.targetObj.find('#headerPoto').attr('src',entity.owner.ownerPicture);
            }
            if(isNotEmpt(entity.chargeMethod)){
                if(entity.chargeMethod==1){//微信支付
                    that.targetObj.find('#wxOut').hide();
                    that.targetObj.find('#wxOutChn').hide();
                    var end = new Date(entity.chargeTime),start = new Date(entity.beginTime);
                    entity.stopTime = GetDateTimeDiff(start.getTime(),end.getTime());
                }
            }
            var isMonth=entity.trafficPermitTypeIdentity==Utils.getModelValueByModelKey(BASIS.TRAFFIC_TYPE_CLASS.MONTH_CLASS);
            var isStor=entity.trafficPermitTypeIdentity==Utils.getModelValueByModelKey(BASIS.TRAFFIC_TYPE_CLASS.STORAGE_CLASS);
            var isTemp=entity.trafficPermitTypeIdentity==Utils.getModelValueByModelKey(BASIS.TRAFFIC_TYPE_CLASS.TEMP_CLASS);
            var isMonthCharge=entity.payType==Utils.getModelValueByModelKey(BASIS.PAY_TYPE.MONTH_CHARGE);
            var isSaveCharge=entity.payType==Utils.getModelValueByModelKey(BASIS.PAY_TYPE.SAVE_CHARGE);
            if((isMonth&&isMonthCharge)||(isStor&&isSaveCharge)){//充值缴费
                that.targetObj.find('#way').hide();
                that.targetObj.find('#umonth').hide();
                if(isStor&&isSaveCharge){
                    that.targetObj.find('#storSpaceCode').hide();
                    that.targetObj.find('#storBeginTime').hide();
                }
            }
            if(isTemp){
                that.targetObj.find('#month').hide();
                that.targetObj.find('#owner').hide();
            }
            if((isMonth&&!isMonthCharge)||(isStor&&!isSaveCharge)){
                that.targetObj.find('#month').hide();
            }
        }
        var discount= chargesList.editResult.discount;
        if(isEmpty(discount)){
            that.targetObj.find('#discount').hide();
        }else{
            if(discount.preferentialType==Utils.getModelValueByModelKey(BASIS.PREFERENTIAL_TYPE.CASH_TICKET)){//代金券
                discount.preferentialContent = '抵免金额 '+(discount.preferentialContent == undefined ? 0 : discount.preferentialContent)+'元';
            }else if(discount.preferentialType==Utils.getModelValueByModelKey(BASIS.PREFERENTIAL_TYPE.DISCOUNT)){//折扣
                discount.preferentialContent = '原收费打 '+(discount.preferentialContent == undefined ? 10 : discount.preferentialContent)+'折';
            }else if(discount.preferentialType==Utils.getModelValueByModelKey(BASIS.PREFERENTIAL_TYPE.REDUCTION)){//减免时间
                discount.preferentialContent = '免收费时长  '+(discount.preferentialContent == undefined ? 0 : discount.preferentialContent)+'分钟';
            }
            discount['preferentialTypeName']=Utils.getModelNameByParentKey(BASIS.PREFERENTIAL_TYPE.ROOT,discount.preferentialType);
        }
        that.sysUtils.setVariantBindFieldValue(chargesList.editResult);
        function GetDateTimeDiff(startMillisecond, endMillisecond) {
            var date = endMillisecond - startMillisecond;   //时间差的毫秒数

            //计算出相差天数
            var days = Math.floor(date / (24 * 3600 * 1000))

            //计算出小时数

            var leave1 = date % (24 * 3600 * 1000);    //计算天数后剩余的毫秒数
            var hours = Math.floor(leave1 / (3600 * 1000));
            //计算相差分钟数
            var leave2 = leave1 % (3600 * 1000);     //计算小时数后剩余的毫秒数
            var minutes = Math.floor(leave2 / (60 * 1000));
            //计算相差秒数
            var leave3 = leave2 % (60 * 1000);  //计算分钟数后剩余的毫秒数
            var seconds = Math.round(leave3 / 1000);
            var temp = 0;
            if(seconds>0){
                temp = 1;
            }
            return days*1440 + hours*60 +  minutes + temp;
        }
    }
}
